package com.bobbygu.googlearchitecture

import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.util.Log
import com.bobbygu.googlearchitecture.bean.Story
import com.bobbygu.googlearchitecture.database.DatabaseManager
import com.bobbygu.googlearchitecture.viewmodel.MyViewModel
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tv2.movementMethod = ScrollingMovementMethod.getInstance()
        DatabaseManager.initDb(this)
        val model = ViewModelProviders.of(this).get(MyViewModel::class.java)
        model.users.observe(this, Observer { users ->
            if (users != null && users.isNotEmpty()) {
                tv1.text = users[0].name
            }
        })

        model.stories.observe(this, Observer { stories ->
            Log.d("Main", "stories:" + stories)
            if (stories != null) {
                var str = ""
                for (story in stories) {
                    str += "title:" + story.title + "\n"
                }
                tv2.text = str
            }
        })

        btn_insert.setOnClickListener {
            DatabaseManager.simlutateInsertData()
        }

        btn_insert_one.setOnClickListener {
            val story = Story()
            story.data = "BobbyApp"
            story.displayData = "BobbyApp displayData"
            story.title = "BobbyApp" + System.currentTimeMillis()
            DatabaseManager.insertStory(story)
        }

        btn_delete_all.setOnClickListener {
            //访问数据库需要到子线程
            Thread({
                DatabaseManager.deleteAllStories()
            }).start()
        }

        btn_delete_one.setOnClickListener {
            DatabaseManager.deleteStory()
        }

        btn_get_data.setOnClickListener {
            DatabaseManager.loadAllStories().observe(this, Observer { stories ->
                model.stories.value = stories
            })
        }
    }
}
